package com.ujoku.controller.admin;


import com.labillusion.core.platform.cdn.upyum.UpYun;
import com.labillusion.core.platform.web.pagination.PaginationView;
import com.labillusion.core.platform.web.rest.RESTController;
import com.labillusion.core.platform.web.rest.exception.InvalidRequestException;
import com.labillusion.core.util.ImageUtils;
import com.labillusion.core.util.StringUtils;
import com.ujoku.domain.GCategory;
import com.ujoku.domain.Goods;
import com.ujoku.domain.GoodsSpec;
import com.ujoku.domain.Winery;
import com.ujoku.request.admin.GoodsForm;
import com.ujoku.request.admin.GoodsPaginationForm;
import com.ujoku.service.GCategoryService;
import com.ujoku.service.GoodsService;
import com.ujoku.service.GoodsSpecService;
import com.ujoku.service.WineryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Greg.Chen on 2015/1/13.
 */

@RestController
public class GoodsMngController extends RESTController {

    @Autowired
    private GCategoryService categoryService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsSpecService goodsSpecService;

    @Autowired
    private WineryService wineryService;

    @Autowired
    private UpYun upyun;

    @Value("#{configProperties['settings.goods.upload']}")
    private String uploadPath;

    @Value("#{configProperties['settings.cdn.goods.upload']}")
    private String cdnUploadPath;

    @RequestMapping(value="/uj-admin/goods/list", method = RequestMethod.POST)
    public PaginationView list(@RequestBody @Valid GoodsPaginationForm form){
        PaginationView<Goods> view = new PaginationView<>();
        int count = goodsService.selectCount(form.getQueryMap());
        view.setCount(count);
        view.setList(goodsService.selectList(form.getQueryMap()));

        return view;
    }

    @RequestMapping(value="/uj-admin/goods/add", method = RequestMethod.POST)
    public Goods add(@RequestBody GoodsForm form){

        Goods goods = new Goods();
        BeanUtils.copyProperties(form, goods);

        setNames(form, goods);

        goodsService.insert(goods);
        return goods;
    }

    private void setNames(GoodsForm form, Goods goods) {
        List<GCategory> categories = categoryService.selectList();
        GCategory c1 = categories.stream().filter(c->c.getCate_id() == form.getCate_id_1()).findFirst().orElse(null);

        GCategory c2 = categories.stream().filter(c->c.getCate_id() == form.getCate_id_2()).findFirst().orElse(null);

        goods.setCate_name_1(c1==null ? null : c1.getCate_name());
        goods.setCate_name_2(c2 == null ? null : c2.getCate_name());

        if(form.getWineryId() != null)
        {
            List<Winery> wineries = wineryService.selectList();
            Winery winery = wineries.stream().filter(w->w.getId() == form.getWineryId()).findFirst().orElse(null);
            if(winery == null)
                throw new InvalidRequestException("can not found winery");
        }

    }

    @RequestMapping(value="/uj-admin/goods", method = RequestMethod.PUT)
    public String update(@RequestBody GoodsForm form){
        Goods goods = new Goods();
        BeanUtils.copyProperties(form, goods);
        setNames(form, goods);



        goodsService.update(goods);

        return "Successfully";
    }

    @RequestMapping(value="/uj-admin/goods/closed", method = RequestMethod.PUT)
    public String updateClosed(@RequestBody GoodsForm form){
        Goods goods = new Goods();
        BeanUtils.copyProperties(form, goods);

        goodsService.update(goods);

        return "Successfully";
    }

    @RequestMapping(value="/uj-admin/goods/{id}", method = RequestMethod.GET)
    public Goods getById(@PathVariable String id){
        Goods goods = (Goods) goodsService.selectById(id);

        String regEx_html="<[^>]+>";
        String description = goods.getDescription();
        if(StringUtils.hasText(description)){
            Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
            Matcher m_html=p_html.matcher(description);
            description = m_html.replaceAll("");
            goods.setDescription(description);
        }

        return goods;
    }

    @RequestMapping(value="/uj-admin/goods/{id}", method = RequestMethod.DELETE)
    public String Delete(@PathVariable String id){

        return null;
    }


    @RequestMapping(value="/uj-admin/goods/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(  @RequestParam MultipartFile file,
                           @RequestParam int id,
                           @RequestParam int index , HttpServletRequest request) throws IOException {

        Goods goods =  goodsService.selectById(id);
        String dir = request.getRealPath(uploadPath);
        File folder = new File(dir);
        if(!folder.exists()){
            folder.mkdirs();
        }


        if(index >= 5){
            String path = dir+"/"+ goods.getGoods_id() + "_desc" + (index - 5) +".jpg";
            File localFile = new File(path);
            file.transferTo(localFile);

            upyun.setContentMD5(UpYun.md5(localFile));
            upyun.writeFile(cdnUploadPath + localFile.getName(), localFile, true);
        }
        else{

            String originalPath = dir+"/"+ goods.getGoods_id() + "_original"+ index +".jpg";
            File originalFile = new File(originalPath);
            //将上传文件写入到指定文件出
            file.transferTo(originalFile);

            String largePath = dir+"/"+ goods.getGoods_id() + "_large"+ index +".jpg";
            ImageUtils.scale2(originalPath, largePath, 800, 800, false);

            String mediumPath = dir+"/"+ goods.getGoods_id() + "_medium"+ index +".jpg";
            ImageUtils.scale2(originalPath, mediumPath, 420, 420, false);

            String smallPath = dir+"/"+ goods.getGoods_id() + "_small"+ index +".jpg";
            ImageUtils.scale2(originalPath, smallPath,80,80, false);

            String[] paths = {largePath, mediumPath , smallPath};
            for(String path : paths){
                File  localFile = new File(path);
                upyun.setContentMD5(UpYun.md5(localFile));
                upyun.writeFile(cdnUploadPath + localFile.getName(), localFile, true);
            }

            originalFile.delete();
        }


        goodsService.update(goods);

        return "Successfully";
    }

    @RequestMapping(value="/uj-admin/inventory/{id}", method = RequestMethod.GET)
    public GoodsSpec getStockById(@PathVariable Integer id){

        return (GoodsSpec)goodsSpecService.selectGoodsSpecById(id);
    }

    @RequestMapping(value="/uj-admin/inventory/edit", method = RequestMethod.PUT)
    public String update(@RequestBody GoodsSpec goodsSpec){
        goodsSpecService.update(goodsSpec);

        return "Successfully";
    }

    @RequestMapping(value="/uj-admin/inventory/add", method = RequestMethod.PUT)
    public String add(@RequestBody GoodsSpec goodsSpec){
        goodsSpecService.insert(goodsSpec);

        return "Successfully";
    }
}
